let express = require("express");
let router = express.Router();
let path = require("path")
let fs = require("fs")
let mysql = require("mysql");
let cookies = require("cookie-parser")
const dayjs = require("dayjs")
let svgcaptcha = require("svg-captcha");
const { promisify } = require("util");
router.use(express.urlencoded({ extended: false }));

//连接数据库
let config = {
    host: "localhost",//数据库连接地址
    port: 3306,//数据库连接端口
    user: "root",//数据库用户名
    password: "root",//数据库密码
    database: "user",//选择要操作的库房
}
let connection = mysql.createConnection(config);
connection.connect((err) => {
    if (err) {
        console.log("数据库连接失败")
    } else {
        console.log("数据库连接成功")
    }
})


//主页
router.get("/index", (req, res) => {
    //res.send("这是首页")
    //判断是否有登录 有登录，则进入到首页，没有登录，则先登录.
    // console.log(req.cookies.username,111)
    res.render("index.html", {
        username: req.cookies.username
    })
    console.log(req.cookies.username);
})

router.get("/index", (req, res) => {
    res.render("./index.html");
})


// let persons = fs.readFileSync(__dirname + "/persons.json", "utf8");
// persons = JSON.parse(persons);

//登录
router.get("/login", (req, res) => {
    // console.log(111)
    res.render("login.html");
})

router.post("/login", (req, res) => {
    let { number, pswd } = req.body;
    // let users = persons.find((item) => {
    //     //console.log(item);
    //     return number == item.username && pswd == item.password;
    // })
    // console.log(number,pswd,req.body);
    let sql = `select * from user_yonghu where username=${number} && password=${pswd}`;
    connection.query(sql, (err, doc) => {
        if (err) {
            console.log("查询失败")
        } else {
            console.log(doc)
            if (doc.length) {
                res.cookie("username", number);
                res.redirect("/index");
            } else {
                res.send("密码或用户名错误");
            }
            // console.log(number,pswd,req.body);
            // if(doc.some(i=>i.username==number&&i.password==pswd)){
            //     console.log("login success")
            // }else{
            //     console.log("login error");
            // }
            // console.log(doc[0].username,1);
            //doc 数据发送给前端 
            // res.render("index.html", { doc: doc })
        }
    })
    // res.send("1")
    // if (users) {
    //     //使用cookie记住用户
    //     res.cookie("username", number);
    //     res.redirect("/index");
    // } else {
    //     res.send("密码或用户名错误");
    // }
})

//注册
router.get("/register", (req, res) => {
    //res.send("登录")
    //登录时候使用cookie记住登录用户名
    //文本框提交的值
    res.render("register.html");
})

router.post("/register", (req, res) => {
    let { number, pswd, yzm } = req.body;
    console.log(req.body);
    // let users = persons.find((item) => {
    //     return number == item.username
    // })
    let sql = `select * from user_yonghu where username=${number}`
    connection.query(sql, (err, doc) => {
        if (doc.length) {
            res.send("用户已存在");
        } else {
            if (yzm == req.cookies.yzm1.toLowerCase()) {
                const time = dayjs().format("YYYY-MM-DD HH:mm:ss")
                console.log(time)

                let sql1 = `insert into user_yonghu (username,password,time) value (${number},"${pswd}","${time}")`;
                connection.query(sql1, (err, doc) => {
                    if (err) {
                        console.log(err)
                        res.send("添加失败")
                    } else {
                        res.redirect("/login");
                        // res.send("添加成功")
                    }
                })
                // persons = JSON.stringify(persons);
                // fs.writeFileSync(__dirname + "/persons.json", persons, { flag: "w" })
            } else {
                res.send("验证码错误");
            }
        }
    })
    // console.log(users);

    // let data = {
    //     username: number,
    //     password: pswd
    // };
    // if (users) {
    //     res.send("用户已存在");
    // } else {
    //     if (yzm == req.cookies.yzm1.toLowerCase()) {
    //         persons.push(data);
    //         persons = JSON.stringify(persons);
    //         fs.writeFileSync(__dirname + "/persons.json", persons, { flag: "w" })
    //         res.redirect("/login");
    //     } else {
    //         res.send("验证码错误");
    //     }

    // }

})

//验证码
router.get("/yzm", (req, res) => {
    let captcha = svgcaptcha.create({});
    res.type("svg");
    res.cookie("yzm1", captcha.text)
    console.log(captcha.text);
    res.send(captcha.data);
})


module.exports = router